import type { Remote } from '@/controller/base/types/remote'
import type { Worker } from '@/controller/base/types/worker'

import { defineStore } from 'pinia'
import { createBaseState, BaseGetters, BaseActions, createBaseApplianceControl } from '../BaseAppliance'
import { RemoteTypes } from '@/controller/base/remote'
import { useWorker, useRemote, wrapSafeActions } from '@/controller/base/index'
import { useAuthStore } from '@/store/auth'
import { useGlobalStore } from '@/store/global'
import store from '@/store'
import type { RefrigeratorBController } from './definition'
import { getAllSetting, getSetting, getSimpleSetting, type ApplianceSetting } from '@/api/appliance'
import { getInventoryList } from '@/api/refrigetorB'
import {
  REFRIGERTORB_LIGHTMODE,
  REFRIGERTORB_HYGIENEMODE,
  REFRIGERTORB_SLIENTMODE,
  REFRIGERTORB_LIGHTBRIGHTNESS,
  REFRIGERTORB_SLIENTMODE_SLEEP_HOUR,
  REFRIGERTORB_SLIENTMODE_SLEEP_MIN,
  REFRIGERTORB_SLIENTMODE_SLEEP_END_HOUR,
  REFRIGERTORB_SLIENTMODE_SLEEP_END_MIN,
  REFRIGERTORB_INVENTORYCONTENT,
  COMMON_STATUS_WIFIOTASTATUS,
} from '@/constants/Command'
import { debounce } from 'lodash'
const authStore = useAuthStore()
const globalStore = useGlobalStore(store)

/**
 * 初始化数据
 */
export const createRefrigeratorBState: () => RefrigeratorBController.State = () => ({
  ...createBaseState(),
  lightMode: 0, // 灯光模式
  hygineMode: 0, // 杀菌模式
  slientMode: 0, // 睡眠模式
  lightBrightNess: 1, // 灯光亮度
  sleepStartHour: 20,
  sleepStartMinute: 0,
  sleepEndHour: 8,
  sleepEndMinute: 0,
  inventoryContent: 0,
  currentMenuGroupKey: '', // 当前显示弹框的设置Key
  currentMenuSettings: null, // 当前显示弹框的设置
  currentInventoryList: [], //当前存储管理列表
  allSettings: [],
  wifiStatus: 0, // ota升级状态
})
export const RefrigeratorBGetters: RefrigeratorBController.Getters = {
  ...BaseGetters,
}
export const RefrigeratorBActions: RefrigeratorBController.Actions = wrapSafeActions<
  RefrigeratorBController.Store,
  RefrigeratorBController.Actions
>({
  ...BaseActions,
  async loadMenuSettings(groupKey: string) {
    this.currentMenuGroupKey = groupKey
    const haId = this._datasource.haId
    const result = await getAllSetting(haId)
    let settings
    if (result.code === 0) {
      settings = result.data.settings
      this.currentMenuSettings = settings.find((items) => items.key === groupKey) as ApplianceSetting
      this.allSettings = settings
    }
  },
})
/**
 * 组合API
 */
const useStore = defineStore<'RefrigeratorB', RefrigeratorBController.State, RefrigeratorBController.Getters>(
  'RefrigeratorB',
  {
    state: createRefrigeratorBState,
    getters: RefrigeratorBGetters,
    actions: RefrigeratorBActions,
  }
)
// 组件使用
export function useRefrigeratorBControl(): RefrigeratorBController.Control {
  const store = useStore() as RefrigeratorBController.Store
  const worker = useWorker(store) as Worker.ApplianceWorker<RefrigeratorBController.Store>
  const remote = useRemote(store) as Remote.ApplianceRemote<RefrigeratorBController.Store>
  return { store, worker, remote }
}
/**
 * 页面使用
 */
export function createRefrigeratorBControl(
  control: RefrigeratorBController.Control = useRefrigeratorBControl()
): RefrigeratorBController.Control {
  const { store, worker, remote } = control
  createBaseApplianceControl(control, { remoteType: RemoteTypes.Oem })
  worker.onLoad(async () => {
    await Promise.all([
      // 加载状态
      // remote.loadAllStatus(),
      remote.loadAllSetting(),
    ])
  })
  // remote.addBatchObserves(RefrigeratorBBatchObserves)
  useRefrigeratorBBinding(control)
  return control
}

// function useRefrigeratorBBinding(control: RefrigeratorBController.Control) {}
export const RefrigeratorBBatchObserves: Remote.BatchObserve<RefrigeratorBController.Store>[] = [
  {
    matcher: () => true,
    // handler() {
    //   this.loadAllSetting()
    //   if (this.store.currentMenuGroupKey) {
    //     this.store.loadMenuSettings(this.store.currentMenuGroupKey)
    //   }
    // },
    handler: debounce((_, remote) => {
      remote.loadAllSetting()
      if (remote.store.currentMenuGroupKey) {
        remote.store.loadMenuSettings(remote.store.currentMenuGroupKey)
      }
    }),
  },
]

export function useRefrigeratorBBinding(control: RefrigeratorBController.Control) {
  const { worker } = control
  // Settings监听
  const syncMap: Partial<Record<keyof RefrigeratorBController.State, string>> = {
    lightMode: REFRIGERTORB_LIGHTMODE,
    hygineMode: REFRIGERTORB_HYGIENEMODE,
    slientMode: REFRIGERTORB_SLIENTMODE,
    lightBrightNess: REFRIGERTORB_LIGHTBRIGHTNESS,
    sleepStartHour: REFRIGERTORB_SLIENTMODE_SLEEP_HOUR,
    sleepStartMinute: REFRIGERTORB_SLIENTMODE_SLEEP_MIN,
    sleepEndHour: REFRIGERTORB_SLIENTMODE_SLEEP_END_HOUR,
    sleepEndMinute: REFRIGERTORB_SLIENTMODE_SLEEP_END_MIN,
    inventoryContent: REFRIGERTORB_INVENTORYCONTENT,
    wifiStatus: COMMON_STATUS_WIFIOTASTATUS,
  }
  Object.entries(syncMap).forEach((entries) => {
    const [prop, key] = entries as [keyof RefrigeratorBController.State, string]
    worker.useGetValueBinding(prop, {
      key,
      from: 'setting',
    })
  })

  // worker.useGetValueBinding('volume_min', {
  //   key: HVN_SETTING_DA_VOLUME,
  //   from: 'setting',
  //   patcher: (patchState, reference) => {
  //     if (reference.item as WS.MessageItem) {
  //       patchState.volume = reference.item.value as number
  //       patchState.volume_min = reference.item.min
  //       patchState.volume_max = reference.item.max
  //     }
  //   },
  // })
}
